package com.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 服务端 ChannelInitializer
 * 
 * @author waylau.com
 * @date 2015-3-13
 */
public class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
	private Class webSocketHandler;
	public WebSocketInitializer(Class webSocketHandler){
		this.webSocketHandler=webSocketHandler;
	}

	@Override
    public void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline;
		try {
			pipeline = ch.pipeline();
			pipeline.addLast(new HttpServerCodec());
			pipeline.addLast(new HttpObjectAggregator(65536*100));//64 * 1024
			pipeline.addLast(new ChunkedWriteHandler());
			pipeline.addLast(new HttpRequestHandler("/"));
			pipeline.addLast(new WebSocketServerProtocolHandler("/"));
			pipeline.addLast((WebSocketHandler)webSocketHandler.newInstance());//TextWebSocketFrameHandler
		}catch (Exception e){
			e.printStackTrace();
		}

//		pipeline.addLast(new OnlineHandler());//TextWebSocketFrameHandler
//		pipeline.addLast(webSocketHandler);//TextWebSocketFrameHandler
	}
}
